﻿Public Class ResizeAdorner
    Inherits Adorner

    Dim visualChildren As VisualCollection
    Dim WithEvents grip As New Thumb With {.Opacity = 0.5}

    Public Sub New(element As UIElement)
        MyBase.New(element)

        visualChildren = New VisualCollection(Me)
        visualChildren.Add(grip)
    End Sub

    Protected Overrides Function MeasureOverride(constraint As Size) As Size
        grip.Measure(New Size(12, 12))
        Return New Size
    End Function

    Protected Overrides Function ArrangeOverride(s As Size) As Size
        Dim bottomRight = New Rect(AdornedElement.DesiredSize).BottomRight
        grip.Arrange(New Rect(bottomRight.X - 6, bottomRight.Y - 6, 12, 12))
        Return New Size
    End Function

    Private Sub grip_DragDelta(sender As Object, e As DragDeltaEventArgs) Handles grip.DragDelta
        Dim clamp As Func(Of Double, Double, Double, Double) = Function(v, max, min) Math.Max(Math.Min(v, max), min)
        Dim element = CType(AdornedElement, FrameworkElement)
        Dim targetWidth = element.ActualWidth + e.HorizontalChange
        Dim targetHeight = element.ActualHeight + e.VerticalChange
        Dim finalSize = clamp(Math.Min(targetWidth, targetHeight), 300, 0.1)
        element.Width = finalSize
        element.Height = finalSize
    End Sub

    Protected Overrides ReadOnly Property VisualChildrenCount As Integer
        Get
            Return visualChildren.Count
        End Get
    End Property

    Protected Overrides Function GetVisualChild(index As Integer) As Visual
        Return visualChildren(index)
    End Function
End Class
